import { Dispatch } from "redux";
import { MyAxios } from "../../../../common/config/http";
import { IAction } from "../../../../common/store/actions";
import { IReducerState_TableFilter } from "./reducer";
import * as Types from "./types";

// 过滤参数
interface ITableFilterRequestParam {
  pageNum: number;
  pageSize: number;
  orderByClause?: string | null;
  keyWords?: string | null;
  filter?: {
    type: number | null | undefined;
  };
}

// 获取table列表
export function getTableDatasourceAct(filter: IReducerState_TableFilter) {
  const data: ITableFilterRequestParam = {
    pageNum: filter.pageNum,
    pageSize: filter.pageSize,
    orderByClause: filter.sortColumn
      ? `${filter.sortColumn} ${filter.sortType}`
      : null,
    keyWords: filter.keyWords ? filter.keyWords : null,
    filter: {
      type: typeof filter.type !== undefined ? filter.type : null
    }
  };
  return (dispatch: Dispatch) => {
    // get data
    dispatch({ type: Types.TABLE.LOADING, data: true });
    MyAxios.axios
      .post("order/user", data, {
        headers: { ...MyAxios.getToken() }
      })
      .then(res => {
        const data = res.data;
        const action: IAction = {
          type: Types.TABLE.DATASOURCE,
          data: data ? data : { list: [], total: 0 }
        };
        dispatch(action);
      })
      .catch(e => {})
      .finally(() => {
        dispatch({ type: Types.TABLE.LOADING, data: false });
      });
  };
}

// 修改table的过滤参数
export function setTableFilterAct(filter: IReducerState_TableFilter): IAction {
  return { type: Types.TABLE.FILTER, data: filter };
}
